package top.zymall.user.util;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;

import java.util.List;

/**
 * @Author: HouZeYu
 * @Description:
 * @Date: Created in 21:52 2018/11/4
 */
@Component
@Slf4j
public class RedisUtils {
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     *
     * @param mobile 手机号
     * @param verifyCode 验证码
     * @param smsVerifyTime 验证码保留时间
     * @return 1 手机号超过验证次数 2 当前验证码未过期 0 验证码 保存成功
     */
    public int saveVerifyCode(String mobile, String verifyCode, int smsVerifyTime) {
      Object result=redisTemplate.execute((RedisCallback) redisConnection -> {
                Jedis jedis= (Jedis) redisConnection.getNativeConnection();
               String mobileCount=jedis.get(mobile+":");
               if (mobileCount!=null && Integer.valueOf(mobileCount)>10){
                   log.error("手机号超过验证次数");
                    return 1;
               }
              Long setnxResult=jedis.setnx(mobile,verifyCode);
               if (setnxResult==0){
                   log.error("当前验证码未过期");
                   return 2;
               }
               jedis.expire(mobile,smsVerifyTime);
            Long mobileincr=   jedis.incr(mobile+":");
               if (mobileincr==1){
                   jedis.expire(mobile+":",862000);
               }
               return 0;

        });
        return (int) result;
    }

    /**
     *   通过手机号得到验证码
     * @param mobile 手机号
     * @return 验证码
     */
    public String getVerifyCodeByMobile(String mobile){
   Object object=redisTemplate.execute((RedisCallback<String>) redisConnection -> {
          Jedis jedis= (Jedis) redisConnection.getNativeConnection();
         return jedis.get(mobile);
      });
     return String.valueOf(object);
    }
}
